package com.zbkj.crmeb.store.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import com.crmeb.core.utils.TableNameUtil;
import com.zbkj.crmeb.front.response.ProductDetailResponse;
import com.zbkj.crmeb.store.request.BatchAssociateNormProductRequest;
import com.zbkj.crmeb.store.response.StoreProductNormInfoResponse;
import com.zbkj.crmeb.store.response.StoreProductStoreInfoResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.github.pagehelper.PageInfo;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.merchant.admin.controller.AdminBaseController;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductDescription;
import com.zbkj.crmeb.store.model.StoreProductNorm;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductNormKeywordResponse;
import com.zbkj.crmeb.store.response.StoreProductNormResponse;
import com.zbkj.crmeb.store.service.StoreProductDescriptionService;
import com.zbkj.crmeb.store.service.StoreProductNormDescriptionService;
import com.zbkj.crmeb.store.service.StoreProductNormService;
import com.zbkj.crmeb.store.service.StoreProductService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 商品表 前端控制器
 * @author muyu
 * @date 2020-10-13
 */
@RestController
@RequestMapping("api/admin/store/product/norm")
@Api(tags = "标准商品") //配合swagger使用
public class StoreProductNormController extends AdminBaseController {
    @Autowired
    private StoreProductNormService storeProductNormService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductNormDescriptionService storeProductNormDescriptionService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    ICategoryMatchService categoryMatchService;

    @ApiOperation(value = "加入标准商品库")
    @PostMapping("/add/{productId}")
    public CommonResult<String> saveNormProduct(@PathVariable Integer productId) {
        Boolean resultStatus = storeProductService.saveNormProduct(productId);
        if(resultStatus) {
            return CommonResult.success();
        }
        
        return CommonResult.failed();
    }

    /**
     * 标准商品国际编码数量统计
     * @Description:  
     * @param @param keyword
     * @throws
     */
    @ApiOperation(value = "标准商品国际编码数量统计")
    @GetMapping("/count/{keyword}")
    public CommonResult<Integer> getNormList(@PathVariable String keyword) {
        int count = storeProductNormService.count(Wrappers.<StoreProductNorm>lambdaQuery()
                .eq(StoreProductNorm::getKeyword, keyword)
        );
        return CommonResult.success(count);
    }

    /**
     * 分页显示商品表(标准商品)
     * @Description:
     * @author daigb
     * @param @param request
     * @param @param pageParamRequest
     * @param @return
     * @return CommonResult<CommonPage<StoreProduct>>
     * @throws
     */
    @ApiOperation(value = "标准商品分页列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<StoreProductNorm>> getNormList(StoreProductSearchRequest request, @Validated PageParamRequest pageParamRequest) {
        PageInfo<StoreProductNorm> pageInfo = storeProductService.getNormList(request, pageParamRequest);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 查询商品表信息
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "标准商品详情")
    @GetMapping("/info/{id}")
    public CommonResult<StoreProductNormResponse> normInfo(@PathVariable Integer id) {
        StoreProductNormResponse storeProductResponse = storeProductService.getSupplierByNormId(id);
        return CommonResult.success(storeProductResponse);
    }

    /**
     * @param keyword Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "标准商品模糊检索")
    @GetMapping("/like/{keyword}")
    public CommonResult<List<StoreProductNormInfoResponse>> normLikeInfo(@PathVariable String keyword, HttpServletRequest servletRequest) throws InvocationTargetException, IllegalAccessException {
        List<StoreProductNorm> storeProductNorms = storeProductNormService.list(Wrappers.<StoreProductNorm>lambdaQuery()
                .likeRight(StoreProductNorm :: getKeyword, keyword)
                );
        //判断分类是否启用
        List<Integer> enableCategoryMatchIds = categoryMatchService.getCategoryMatchIds(getMerId(servletRequest));
        storeProductNorms.forEach(storeProductNorm -> {
            boolean enableCategoryBool = !enableCategoryMatchIds.contains(storeProductNorm.getCateId());
            if (enableCategoryBool){
                storeProductNorm.setCateId(null);
            }
        });

        List<StoreProductNormInfoResponse> responses = new ArrayList<>();
        for (StoreProductNorm item : storeProductNorms){
            StoreProductNormInfoResponse productNormInfo = new StoreProductNormInfoResponse();
            BeanUtils.copyProperties(item, productNormInfo);

            Integer productId = storeProductService.lambdaQuery().eq(StoreProduct::getBarCode, item.getBarCode()).one().getId();
            StoreProductDescription description = storeProductDescriptionService.lambdaQuery().eq(StoreProductDescription::getProductId, productId).one();
            productNormInfo.setGwmt1(description.getGwmt1())
                    .setGwpp1(description.getGwpp1())
                    .setSp(description.getSp())
                    .setSp1(description.getSp1())
                    .setSp2(description.getSp2())
                    .setSp3(description.getSp3())
                    .setMt(description.getMt())
                    .setMt1(description.getMt1())
                    .setMx1(description.getMx1());

            responses.add(productNormInfo);
        }

        return CommonResult.success(responses);
    }

    /**
     * @param keyword Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "标准商品精确检索")
    @GetMapping("/get/{keyword}")
    public CommonResult<StoreProductNorm> normInfo(@PathVariable String keyword) {
        StoreProductNorm storeProductNorm = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
                .eq(StoreProductNorm :: getKeyword, keyword)
                .last("LIMIT 1")
                );
        
        return CommonResult.success(storeProductNorm);
    }

    /**
     * 新增商品表
     * @param storeProductNorm 新增参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "新增")
    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> save(@RequestBody @Validated StoreProductNorm storeProductNorm) {
        int isNorm = storeProductNormService.count(Wrappers.<StoreProductNorm>lambdaQuery()
                .eq(StoreProductNorm :: getKeyword, storeProductNorm.getKeyword())
                );
        if(isNorm > 0) {
            return CommonResult.failed("该国际公码已存在");
        }
        //设置重量
        CategoryMatch categoryMatch = categoryMatchService.getById(storeProductNorm.getCateId());
        if (Objects.isNull(storeProductNorm.getWeight())){
            storeProductNorm.setWeight(categoryMatch.getWeight());
        }
        storeProductNorm.setStoreInfo("");
        boolean b = storeProductNormService.save(storeProductNorm);
        if (b) {
            storeProductNormDescriptionService.saveStoreProductNormDescription(storeProductNorm.getId(), storeProductNorm.getStoreInfo());
        }
        // 处理富文本
        return b ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 修改商品表
     * @param storeProductNorm 修改参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "修改")
    @PutMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> update(@RequestBody @Validated StoreProductNorm storeProductNorm) {
        int count = storeProductNormService.count(Wrappers.<StoreProductNorm>lambdaQuery()
                .eq(StoreProductNorm::getKeyword, storeProductNorm.getKeyword()).ne(StoreProductNorm::getId, storeProductNorm.getId()));
        if(count > 0){
            return CommonResult.failed("该国际公码已存在");
        }
        storeProductNorm.setIsChange(true);
        //设置重量
        CategoryMatch categoryMatch = categoryMatchService.getById(storeProductNorm.getCateId());
        if (Objects.isNull(storeProductNorm.getWeight())){
            storeProductNorm.setWeight(categoryMatch.getWeight());
        }
    	boolean update = storeProductNormService.updateById(storeProductNorm);
        if (update) {
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .set(StoreProduct :: getStoreName, storeProductNorm.getStoreName())
                    .set(StoreProduct :: getColorCode, storeProductNorm.getColorCode())
                    .set(StoreProduct :: getSeasonCode, storeProductNorm.getSeasonCode())
                    .set(StoreProduct :: getBrandId, storeProductNorm.getBrandId())
                    .set(StoreProduct :: getBrandName, storeProductNorm.getBrandName())
                    .set(StoreProduct :: getCateId, storeProductNorm.getCateId())
                    .eq(StoreProduct :: getNormId, storeProductNorm.getId())
            );
            storeProductNormDescriptionService.updateStoreProductNormDescription(storeProductNorm.getId(), storeProductNorm.getStoreInfo());
        }
        return update ? CommonResult.success() : CommonResult.failed();
    }
    
    @ApiOperation(value = "国际编码对云仓商品列表")
    @GetMapping("/keywords")
    public CommonResult<PageInfo<StoreProductNormKeywordResponse>> keywordPage(StoreProductSearchRequest request) {
        return CommonResult.success(storeProductService.pageNormKeywords(request));
    }
    
    @ApiOperation(value = "云仓绑定标准商品")
    @PutMapping("/{productId}/bind/{normKeywords}")
    public CommonResult<String> bindNorm(@PathVariable Integer productId, @PathVariable String normKeywords) {
        StoreProductNorm norm = storeProductNormService.getOne(Wrappers.<StoreProductNorm>lambdaQuery()
                .eq(StoreProductNorm :: getKeyword, normKeywords)
                .last("LIMIT 1")
                );
        if(null == norm) {
            return CommonResult.failed("该国际公码的标准商品不存在");
        }
        
        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                .eq(StoreProduct :: getId, productId)
                .set(StoreProduct :: getStoreName, norm.getStoreName())
//                .set(StoreProduct :: getComposition, norm.getComposition())
//                .set(StoreProduct :: getDimension, norm.getDimension())
                .set(StoreProduct :: getColorCode, norm.getColorCode())
                .set(StoreProduct :: getSeasonCode, norm.getSeasonCode())
//                .set(StoreProduct :: getImage, norm.getImage())
//                .set(StoreProduct :: getSliderImage, norm.getSliderImage())
                .set(StoreProduct :: getBrandId, norm.getBrandId())
                .set(StoreProduct :: getBrandName, norm.getBrandName())
                .set(StoreProduct :: getCateId, norm.getCateId())
                .set(StoreProduct :: getNormId, norm.getId())
                );
        
        // 更新商品描述
        StoreProductDescription storeProductDescription = Optional.ofNullable(
        		storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaUpdate()
	        		.eq(StoreProductDescription :: getProductId, productId)
	        		.last("LIMIT 1")
        		)).orElse(new StoreProductDescription());
        storeProductDescription.setProductId(productId);
        storeProductDescription.setComposition(norm.getComposition());
        storeProductDescription.setDimension(norm.getDimension());
        storeProductDescription.setDescription(norm.getStoreInfo());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);
        
        return CommonResult.success();
    }

    @ApiOperation(value = "批量关联标准商品库")
    @PostMapping("/batch/associate")
    public CommonResult<String> batchAssociateNormProduct(@RequestBody BatchAssociateNormProductRequest request) {
        return storeProductService.batchAssociateNormProduct(request) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete/{id}")
    public CommonResult<String> delete(@PathVariable Integer id) {
        return storeProductNormService.deleteNormProduct(id) ? CommonResult.success() : CommonResult.failed();
    }

}
